package com.kaida.kaidaquery.controller;

import com.kaida.kaidaquery.exception.QueryException;
import com.kaida.kaidaquery.service.ServiceImpl;
import com.kaida.kaidaquery.util.IdCardVerification;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author zxm
 * @date 2020/9/19 20:50
 */
@Controller
@RequestMapping("")
public class IndexController {

    @Autowired
    ServiceImpl service;

    @GetMapping("")
    public String index() {
        return "index";
    }

    @GetMapping("/index")
    public String index1() {
        return "index";
    }

    @GetMapping("/query")
    public String query() {
        return "index";
    }


    @PostMapping("query")
    public String query(String name, String authKey, Model model) {
        model.addAttribute("name", name);
        model.addAttribute("authKey", authKey);
        try {
            check(name, authKey);
        } catch (QueryException e) {
            model.addAttribute("err", e.getMessage());
            return "index";
        }
        try {
            model.addAttribute("major", service.query(name, authKey));
        } catch (Exception e) {
            e.printStackTrace();
            String err = "出现未知错误,请反馈";
            if (e instanceof QueryException) {
                err = e.getMessage();
            }
            model.addAttribute("err", err);
        }
        return "index";
    }

    private void check(String name, String authKey) throws QueryException {
        if (StringUtils.isEmpty(name)) {
            throw new QueryException("请输入姓名");
        }
        if (StringUtils.isEmpty(authKey)) {
            throw new QueryException("请输入身份证");
        }
        String validate = IdCardVerification.IDCardValidate(authKey);

        if (!validate.equals(IdCardVerification.VALIDITY)) {
            throw new QueryException(validate);
        }
    }
}
